/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufpr.tads.suck.Controller;

import br.ufpr.tads.suck.model.AvisoException;
import br.ufpr.tads.suck.model.Endereco;
import br.ufpr.tads.suck.model.Pessoa;
import br.ufpr.tads.suck.model.Plano;
import br.ufpr.tads.suck.model.PlanoDao;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 *
 * @author G0006185
 */
@WebServlet(name = "PlanoServ", urlPatterns = {"/PlanoServ"})
public class PlanoServ extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
         String metodo = request.getParameter("action");
         Plano plano = new Plano();
         Endereco endereco = new Endereco();
         try {
             PlanoDao planoDao = new PlanoDao();
             
             if (metodo.equalsIgnoreCase("add")) {

                 plano.setNome(request.getParameter("nome"));
                 plano.setCnpj(request.getParameter("cnpj").replaceAll("\\D", ""));
                 plano.setContato(request.getParameter("contato"));
                 plano.setEmail(request.getParameter("email"));
                 plano.setTelefone(request.getParameter("tel").replaceAll("\\D", ""));
                 endereco.setLogradouro(request.getParameter("endereco"));
                 endereco.setNumero(Integer.parseInt(request.getParameter("numero")));
                 endereco.setCidade(request.getParameter("cidade"));
                 endereco.setBairro(request.getParameter("bairro"));
                 endereco.setEstado(request.getParameter("uf"));
                 plano.setEndereco(endereco);
                 
                 
                 if(request.getParameter("id").length()>0){
                        plano.setId(Integer.parseInt(request.getParameter("id")));
                        planoDao.upPlano(plano);
                    }else{
                        planoDao.addPlano(plano);
                    }
              
                 
                 
             } else if (metodo.equalsIgnoreCase("list")) {
                 System.out.println(metodo);
                     JSONArray list = new JSONArray();
                    for (Plano planos : planoDao.listPlano()) {
                        JSONObject obj=new JSONObject();
                        obj.put("nome", planos.getNome());
                        obj.put("cnpj", planos.getCnpj());
                        obj.put("email", planos.getEmail());
                        obj.put("id", planos.getId());
                        obj.put("tel", planos.getTelefone());
                        obj.put("contato",planos.getContato());
                        obj.put("uf", planos.getEndereco().getEstado());
                        obj.put("cidade", planos.getEndereco().getCidade());
                        obj.put("numero", planos.getEndereco().getNumero());
                        obj.put("bairro", planos.getEndereco().getBairro());

                        list.add(obj);
                        
                    }
                    out.println(list);
             }else if (metodo.equalsIgnoreCase("one")) {
                    
                    Plano planos = planoDao.listPlano(Integer.parseInt(request.getParameter("id")));
                    JSONObject obj = new JSONObject();
                        obj.put("nome", planos.getNome());
                        obj.put("cnpj", planos.getCnpj());
                        obj.put("email", planos.getEmail());
                        obj.put("id", planos.getId());
                        obj.put("tel", planos.getTelefone());
                        obj.put("contato",planos.getContato());
                        
                        obj.put("uf", planos.getEndereco().getEstado());
                        obj.put("cidade", planos.getEndereco().getCidade());
                        obj.put("numero", planos.getEndereco().getNumero());
                        obj.put("bairro", planos.getEndereco().getBairro());
                        obj.put("endereco", planos.getEndereco().getLogradouro());
                    out.println(obj);
                    System.out.println(obj);
             }else if (metodo.equalsIgnoreCase("del")) {
                    planoDao.delPlano(Integer.parseInt(request.getParameter("id")));
                    
             }else if(metodo.equalsIgnoreCase("search")){
                   
                    System.out.println(metodo);
                     JSONArray list = new JSONArray();
                     
                    
                    for (Plano Planos : planoDao.listPlano(request.getParameter("cnpj").replaceAll("\\D", ""))) {
                        JSONObject obj=new JSONObject();
                        obj.put("nome", Planos.getNome());
                        obj.put("cnpj", Planos.getCnpj());
                        obj.put("email", Planos.getEmail());
                        obj.put("id", Planos.getId());
                        obj.put("tel", Planos.getTelefone());
                        obj.put("uf", Planos.getEndereco().getEstado());
                        obj.put("cidade", Planos.getEndereco().getCidade());
                        obj.put("numero", Planos.getEndereco().getNumero());
                        obj.put("bairro", Planos.getEndereco().getBairro());

                        list.add(obj);
                        
                    }
                    out.println(list);
                    System.out.println(list);
                }
             
             
         } catch (FileNotFoundException | ClassNotFoundException |NoSuchAlgorithmException|  SQLException  | AvisoException ex) {
                JSONObject e=new JSONObject();
                
                e.put("erro",ex.getMessage());
                out.println(e);
                System.out.println(e);
               
            } catch (NumberFormatException e){
              JSONObject er=new JSONObject();
                er.put("erro","Campo Numerico "+e.getMessage());
                out.println(er);
                System.out.println(e);
                
            }
         
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
